package com.wangjiyuan.giftshuo.widget;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridLayout;
import android.widget.LinearLayout;

import java.util.List;

/**
 * Created by wjy on 2016/11/16.
 */

public class BannerItem extends LinearLayout {
    private ViewPager ad_banner;
    private GridLayout secondary_banner;
    public static final int SECONDARY_WIDTH = 375;
    public static final int SECONDARY_HEIGHT = 285;
    public static final int AD_WIDTH = 700;
    public static final int AD_HEIGHT = 365;
    private int adHeight;
    private int secondaryHeight;
    private int widthSize;

    public BannerItem(Context context) {
        this(context, null);
    }

    public BannerItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        ad_banner = new ViewPager(getContext());
        LayoutParams layoutParam1 = new LayoutParams(widthSize, adHeight);
        ad_banner.setLayoutParams(layoutParam1);

        addView(ad_banner);

        secondary_banner = new GridLayout(getContext());
        LayoutParams layoutParam2 = new LayoutParams(widthSize, secondaryHeight);
        secondary_banner.setLayoutParams(layoutParam2);
        secondary_banner.setColumnCount(3);
        secondary_banner.addView(secondary_banner);
    }

    @Override
    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
        super.measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        switch (widthMode) {
            case MeasureSpec.EXACTLY:
                adHeight = widthSize * AD_HEIGHT / AD_WIDTH;
                secondaryHeight = widthSize * SECONDARY_WIDTH * 3 / (2 * SECONDARY_HEIGHT);
                setMeasuredDimension(widthSize, adHeight + secondaryHeight);
                break;
        }
    }

    public void setAdapter(PagerAdapter adapter) {
        ad_banner.setAdapter(adapter);
    }

    public void addView(List<View> views) {
        for (View view :
                views) {
            secondary_banner.addView(view);
        }
    }
}
